<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import {primaryColor_rgb,primaryColorFade} from "@/theme/config"
import { navTags as useNavTags } from '@/store'
import {Close} from '@element-plus/icons-vue'
import sortable from 'sortablejs'

onMounted(() => {
	const dragArea = tagsRef.value
	const ops = {
		animation: 100,
    dataIdAttr: 'itemId',
		onEnd: (_evt: any) => {
			elDropdownRef.value.forEach((v:any)=>v.handleClose())   
      setTimeout(()=>{navTags.setSort(sortableInstance.toArray())},100)
		},
	}
	//初始化
	const sortableInstance = sortable.create(dragArea, ops)
})

const elDropdownRef=ref()
const tagsRef = ref()
const navTags = useNavTags()
const router = useRouter()
const bgColor=primaryColorFade(0.3)
const textColor=primaryColor_rgb

function bindCloseTag(index: number) {
	//console.log(index,navTags.tags)
	navTags.deleteTag(index)
}
function bindGo(item: any) {
	router.push(item.fullPath)
}
</script>

<template>
	<el-scrollbar >
	<div class="tagNavBar">
		<div class="tags" ref="tagsRef">
			<el-dropdown trigger="contextmenu" v-for="(item, index) in navTags.tags" :key="item.name" :itemId="item.name" ref="elDropdownRef">
				<div :class="{ tag: true, active: item.active }" @click="bindGo(item)" >
					<span class="title">{{ item.title }}</span>
					<el-icon style="font-size: 13px" v-if="!item.affix" @click.stop="bindCloseTag(index)"><Close /></el-icon>
				</div>
				<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item @click="navTags.deleteTag(index)" :disabled="item.affix">关闭当前</el-dropdown-item>
						<el-dropdown-item @click="navTags.clearRightTags(index)">关闭右侧</el-dropdown-item>
						<el-dropdown-item @click="navTags.clearLeftTags(index)">关闭左侧</el-dropdown-item>
						<el-dropdown-item @click="navTags.clearOtherTags(index)">关闭其他</el-dropdown-item>
						<el-dropdown-item @click="navTags.clearTags(false)">关闭所有</el-dropdown-item>
					</el-dropdown-menu>
				</template>
			</el-dropdown>
		</div>
		<span class="limitTip" v-show="navTags.tags.length == navTags.maxLength">数量已达上限</span>
	</div>
</el-scrollbar>
</template>

<style scoped lang="scss">
.tagNavBar {
	width: 100%;
	height: 38px;
	padding: 10px 12px 0;
	padding-top: 10px;
	display: flex;

	.tags {
		display: flex;
	}
	.tag {
		text-align: center;
		background-color: rgb(221, 221, 221,.3);
		margin-right: 5px;
		padding: 6px 10px;
		border-radius: 5px 5px 0 0;
		cursor: pointer;
		white-space: nowrap;
		user-select: none;

		.title {
			font-size: 13px;
			margin-right: 5px;
		}
	}
	.active {
		background-color: v-bind(bgColor);
		color: v-bind(textColor);
	}
	.limitTip {
		align-self: flex-end;
		font-size: 12px;
		color: red;
		white-space: nowrap;
	}
	:deep(.el-dropdown .el-dropdown-link){
      outline: none;
	}
}
</style>
